package com.itheima.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
/**
 * @author : [chenxys]
 * @version : [v1.0]
 * @Description : 处理会员相关操作
 * @createTime : [2022/5/30 14:10]
 */
@RestController
@RequestMapping(value = "/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    /**
     * 用户使用验证码快速登录
     * @author chenxys
     * @param response 携带cookie信息
     * @param map 接收传入的参数
     * @return com.itheima.entity.Result
     */
    @RequestMapping(value = "/login")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        //1、校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
        //获取手机号码
        String telephone = (String) map.get("telephone");
        //获取redis中的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //获取提交的验证码
        String validateCode = (String) map.get("validateCode");
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)){
            //验证码正确
            //2、如果验证码正确，则判断当前用户是否为会员，如果不是会员则自动注册为会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null){
                //如果不是会员则自动注册为会员
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //3、向客户端写入cookie，内容为用户手机号
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            //路径
            cookie.setPath("/");
            //有效期
            cookie.setMaxAge(60*60*24*30);
            //将cookie写入浏览器客户端
            response.addCookie(cookie);
            //4、将会员信息保存到redis，使用手机号码作为key，保存时长为30分钟
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }else {
            //验证码错误
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
